package eaa.tgi.scrum.repositories;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import eaa.tgi.scrum.domain.User;

@Repository
public class UserRepository {

	protected EntityManager entityManager;
	
	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}
	
	public User findByUsernameAndPassword(String username, String password) {
		
		try {
		
			User user = (User) entityManager.createQuery("SELECT u FROM User u WHERE u.username = :username AND u.password = :password")
												  .setParameter("username", username)
												  .setParameter("password", password).getSingleResult();	
		
			return user;
			
		} catch (NoResultException userNotFoundException) {
			return null;
		}
	}
	
	public void update(User u) {
		entityManager.persist(u);
	}
}
